package modules.load
{
	import flash.events.Event;
	
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	import br.com.stimuli.loading.loadingtypes.LoadingItem;
	
	import modules.ModuleManager;

	public class LoadManager extends ModuleManager
	{
		public var loader:BulkLoader;
		

		public function LoadManager()
		{
			initLoader();

			addListeners();
		}

		private function initLoader():void
		{
			// creates a BulkLoader instance with a name of "main-site", that can be used to retrieve items without having a reference to this instance
			loader = new BulkLoader("main-site");
			// set level to verbose, for debugging only
			loader.logLevel = BulkLoader.LOG_ERRORS;

			// dispatched when ALL the items have been loaded:
			loader.addEventListener(BulkLoader.COMPLETE, onAllItemsLoaded);

			// dispatched when any item has progress:
			loader.addEventListener(BulkLoader.PROGRESS, onAllItemsProgress);
		}

		private function addListeners():void
		{
			dispatcher.addEventListener(LoadEvent.LOAD_RESOURCE, onLoadResource);
		}

		private function onLoadResource(event:LoadEvent):void
		{
			for each (var url:String in event.data.urls)
			{
				loader.add(url);
				loader.get(url).addEventListener(BulkLoader.COMPLETE, onSingleComplete);
			}
			if (!loader.isRunning)
				loader.start();
		}

		private function onSingleComplete(event:Event):void
		{
			var loadingItem:LoadingItem = event.target as LoadingItem;

			loader.get(loadingItem.url.url).removeEventListener(BulkLoader.COMPLETE, onSingleComplete);

			dispatcher.dispatchEvent(new LoadEvent(LoadEvent.LOAD_SINGLE_COMPLETE, loadingItem));
		}

		public function onAllItemsLoaded(evt:Event):void
		{
			logger("every thing is loaded!");
		}

		// this evt is a "super" progress event, it has all the information you need to 
		// display progress by many criterias (bytes, items loaded, weight)
		public function onAllItemsProgress(evt:BulkProgressEvent):void
		{
//			logger(evt.loadingStatus());
		}

	}
}
